<?php

namespace common\models;

use Yii;

/**
 * This is the model class for table "{{%menu}}".
 *
 * @property string $id
 * @property string $title
 * @property string $url
 * @property string $sort
 * @property string $create_time
 * @property string $pid
 * @property string $group
 * @property integer $status
 */
class Menu extends \yii\db\ActiveRecord
{
	public $pname;
	public $tree;
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%menu}}';
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
			[['title'], 'required'],
            [['sort', 'create_time', 'pid', 'status', 'hide'], 'integer'],
            [['title', 'url', 'groups', 'icon'], 'string', 'max' => 50]
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'title' => '标题',
            'url' => 'URL',
            'sort' => '排序',
            'create_time' => '创建时间',
            'pid' => '上级菜单',
			'icon' => '图标',
            'groups' => '所属分组',
			'hide'  => '是否隐藏',
            'status' => '状态',
        ];
    }

	/**
	 * 新增菜单的方法
	 */
	public function add(){
		$this->sort = intval($this->sort);
		$this->create_time = time();

		return $this->insert();
	}
	
	/**
	 * 更新
	 */
	public function edit(){
		$this->sort = intval($this->sort);

		return $this->save();
	}

	/**
	 * 获取顶级菜单 （pid为0的一级菜单）
	 */
	public function getTopMenu(){
		$list = $this->find()->where(['status' => 1, 'pid' => 0])->orderBy('sort')->all();
		/* 组装成下来列表样式 */
		$arr[0] = '顶级菜单';
		foreach ($list as $val) {
			$arr[$val->id] = $val->title;
		}
		return $arr;
	}

	/**
	 * 获取父类的名称
	 * @param  $pid  父类的id
	 */
	public function getPname($pid){
		$data = $this->find()->where('id=' . $pid)->one();
		return $data->title;
	}

	/**
	 * 获取pid = 0 的一级菜单
	 */
	public function getTop(){
		return $this->find()->where(['status' => 1, 'pid' => 0])->orderBy('sort')->all();
	}


}
